#include "confdeal.h"

#include <vector>
#include <string>
#include <QSettings>
#include <QDir>
#include <QDebug>
#include <QString>
#include <QStringList>
#include <QCoreApplication>

/*
**将字符串按指定标识分段
*/
inline bool string_divide( std::vector<std::string> &_strlist,const std::string src,const std::string div)
{
	std::string _src = src;
	std::string::size_type _pos = _src.find(div);
	while(std::string::npos != _pos)
	{
		std::string _buf = "";
		_buf = _src.substr(0,_pos);
		_strlist.push_back(_buf);
		_src = _src.erase(0,_pos+div.size());
		_pos = _src.find(div.c_str());
	}
	if(!_src.empty()){
		_strlist.push_back(_src);
	}
	return true;
};

ConfDeal* ConfDeal::instance = NULL;
ConfDeal* ConfDeal::getInstance(bool _iniSetf)
{
    if(NULL == ConfDeal::instance)
    {
        ConfDeal::instance = new ConfDeal(_iniSetf);
    }
    return ConfDeal::instance;
};

void ConfDeal::Destroy()
{
	if(NULL!=ConfDeal::instance){
		delete ConfDeal::instance;
		ConfDeal::instance = NULL;
	}
};

ConfDeal::ConfDeal(bool _iniSetf) : iniSetf(_iniSetf)
{
	init();
};

ConfDeal::~ConfDeal()
{
};

void ConfDeal::init()
{
	initconf();
	if (iniSetf)
	{
		readconfQt();
		printfconf();
	}
};

void ConfDeal::initconf()
{
	appDir = QCoreApplication::applicationDirPath();
	divPath="/";
	#ifdef WIN32
	appDir = appDir.replace("/","\\");
	divPath="\\";
	#endif
	qDebug() << " appDir = " << appDir << "\n";
};

void ConfDeal::readconfQt()
{
	QString _confFile = "conf.ini";
	settings=new QSettings(_confFile,QSettings::IniFormat);
	settings->setIniCodec( "UTF-8");
};

void ConfDeal::printfconf()
{
	initSet();
	QStringList groups = settings->childGroups();
	// if (groups.empty())
	// {
	// 	initSet();
	// }
	foreach(QString group,groups)
    {
    	qDebug()<<QString("....................[%1]..................").arg(group);
        settings->beginGroup(group);
        QStringList keyList=settings->childKeys();
        foreach(QString key,keyList)
        {
			qDebug()<<key<<"="<<settings->value(key).toString();
        }
        settings->endGroup();
    }
};

void ConfDeal::initSet()
{
	//
	getdbDir();
};

QStringList ConfDeal::getListFromStr(QString _str)
{
    return _str.split(",", QString::SkipEmptyParts);
};

QString ConfDeal::getappDir()
{
	return appDir;
};

QString ConfDeal::getpathDiv()
{
	return divPath;
};

/////////////////////////////////General//////////////////////////////////////////

QString ConfDeal::getdbDir()
{
	if (!settings->contains("DIR/dbDir"))
	{
		settings->setValue("DIR/dbDir",(appDir+divPath+"gadata"));
		settings->setValue("DIR-note/dbDir",QObject::tr("note-dbDir"));
	}
	return settings->value("DIR/dbDir").toString();
};
